﻿using MTQ.BLL;
using MTQ.IBLL;
using MTQ.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MTQ.Common;

namespace MTQ.Web.Controllers
{
    public class Base_KeyValueController : BaseController
    {

        private IBase_KeyValueService iBase_KeyValueService = new Base_KeyValueService();
        //
        // GET: /Base_KeyValue/

        public ActionResult Index()
        {
            ViewBag.KeyValueName = Base_LocalService.GetWord("KeyValueName", CultureInfoName);

            return View();
        }


        [AccountAuth(Roles = "Base_KeyValue_Create")]
        public ActionResult Create()
        {
            var parentid = GetRequestQueryString("parentid");
            Guid id = new Guid(parentid);

            Base_KeyValue parentEntity = iBase_KeyValueService.LoadEntities(x => x.KeyValue_ParentId == id).OrderByDescending(x => x.KeyValue_Sort).FirstOrDefault();
            if (parentEntity == null)
            {
                ViewBag.Sort = 10;
            }
            else
            {
                ViewBag.Sort = parentEntity.KeyValue_Sort + 10;
            }

            ViewBag.KeyValueName = Base_LocalService.GetWord("KeyValueName", CultureInfoName);
            //ViewBag.parentid = parentid;
            return View();
        }

        [HttpPost]
        [AccountAuth(Roles = "Base_KeyValue_Create")]
        public ActionResult Create(Base_KeyValue KeyValue)
        {
            ModelMessage listMsg = new ModelMessage();

            if (ModelState.IsValid)
            {
                Base_KeyValue parentEntity = iBase_KeyValueService.LoadEntities(x => x.KeyValue_Id == KeyValue.KeyValue_ParentId).OrderByDescending(x => x.KeyValue_Sort).FirstOrDefault();

                KeyValue.KeyValue_Level = ++parentEntity.KeyValue_Level;
                KeyValue.KeyValue_Id = System.Guid.NewGuid();
                KeyValue.CreateDateTime = System.DateTime.Now;

                KeyValue.CreateUserId = CurrentUserInfo.User_Id;
                KeyValue.CreateUserName = CurrentUserInfo.User_UserName;
                KeyValue.KeyValue_Available = "Y";

                KeyValue.KeyValue_Code = parentEntity.KeyValue_Code + "" + (KeyValue.KeyValue_Sort + 1000).ToString().Substring(1);

                var result = iBase_KeyValueService.AddEntity(KeyValue);
                listMsg = new ModelMessage("ChangeResult", "m001", result != null ? "保存成功" : "保存失败");
            }
            return Json(listMsg);
        }


        [AccountAuth(Roles = "Base_KeyValue_Create")]
        public ActionResult CreateCustom()
        {

            //Guid id = new Guid("00000000-0000-0000-0000-000000000000");

            //Base_KeyValue parentEntity = iBase_KeyValueService.LoadEntities(x => x.KeyValue_ParentId == id).OrderByDescending(x => x.KeyValue_Sort).FirstOrDefault();
            //if (parentEntity == null)
            //{
            //    ViewBag.Sort = 10;
            //}
            //else
            //{
            //    ViewBag.Sort = parentEntity.KeyValue_Sort + 10;
            //}

            //ViewBag.parentid = parentid;
            ViewBag.KeyValueName = Base_LocalService.GetWord("KeyValueName", CultureInfoName);
            return View();
        }

        [HttpPost]
        [AccountAuth(Roles = "Base_KeyValue_Create")]
        public ActionResult CreateCustom(Base_KeyValue KeyValue)
        {
            ModelMessage listMsg = new ModelMessage();

            if (ModelState.IsValid)
            {             

                KeyValue.KeyValue_Level = 1;
                KeyValue.KeyValue_Id = System.Guid.NewGuid();
                KeyValue.CreateDateTime = System.DateTime.Now;

                KeyValue.CreateUserId = CurrentUserInfo.User_Id;
                KeyValue.CreateUserName = CurrentUserInfo.User_UserName;
                KeyValue.KeyValue_Available = "Y";
                KeyValue.KeyValue_ParentId = new Guid("00000000-0000-0000-0000-000000000000");
                KeyValue.KeyValue_CompanyCode = "Customer";

                KeyValue.KeyValue_Code = RandNumber.Str(3, true);

                var result = iBase_KeyValueService.AddEntity(KeyValue);
                listMsg = new ModelMessage("ChangeResult", "m001", result != null ? "保存成功" : "保存失败");
            }
            return Json(listMsg);
        }

        [AccountAuth(Roles = "Base_KeyValue_Index")]
        public ActionResult Search()
        {
            List<Base_KeyValue> list = iBase_KeyValueService.LoadEntities(x => x.KeyValue_Available == "Y").OrderBy(x => x.KeyValue_Sort).ToList();

            string keyword = GetRequestQueryString("keyword");

            List<Base_KeyValue> searchResult = null;

            if (string.IsNullOrEmpty(keyword))
            {
                searchResult = list;
            }
            else
            {
                List<Base_KeyValue> searchlist = list.Where(x => x.KeyValue_Name.Contains(keyword)).ToList();
                //添加所有的子节点
                List<Base_KeyValue> listAddSun = new List<Base_KeyValue>();
                foreach (var item in searchlist)
                {
                    KeyValueAddSum(item, listAddSun, list);
                }

                //添加所有的父节点
                List<Base_KeyValue> listAddParent = new List<Base_KeyValue>();
                foreach (var item in searchlist)
                {
                    listAddParent.Add(item);
                }
                foreach (var item in searchlist)
                {
                    KeyValueAddParent(item, listAddParent, list);
                }

                //汇总
                searchResult = listAddParent;
                foreach (var item in listAddSun)
                {
                    searchResult.Add(item);
                }
            }

            ServertLayuiTable<Base_KeyValue> servertBootStrapTable = new ServertLayuiTable<Base_KeyValue>();
            servertBootStrapTable.code = 0;
            servertBootStrapTable.count = searchResult.Count();
            servertBootStrapTable.data = searchResult;
            servertBootStrapTable.msg = "";

            return Json(servertBootStrapTable, JsonRequestBehavior.AllowGet);
        }

        private void KeyValueAddParent(Base_KeyValue item, List<Base_KeyValue> searchlist, List<Base_KeyValue> list)
        {
            if (item.KeyValue_ParentId != new Guid("00000000-0000-0000-0000-000000000000") && searchlist.Where(x => x.KeyValue_Id == item.KeyValue_ParentId).Count() == 0)
            {
                Base_KeyValue KeyValue = list.Where(x => x.KeyValue_Id == item.KeyValue_ParentId).FirstOrDefault();
                if (KeyValue == null) {
                    return;
                }
                searchlist.Add(KeyValue);
                KeyValueAddParent(KeyValue, searchlist, list);
            }

        }

        private void KeyValueAddSum(Base_KeyValue item, List<Base_KeyValue> searchlist, List<Base_KeyValue> list)
        {

            foreach (var item2 in list.Where(x => x.KeyValue_ParentId == item.KeyValue_Id).ToList())
            {
                searchlist.Add(item2);
                KeyValueAddSum(item2, searchlist, list);
            }
        }



        [AccountAuth(Roles = "Base_KeyValue_Edit")]
        public ActionResult Edit(Guid? primarykey)
        {
            Base_KeyValue KeyValue = iBase_KeyValueService.LoadEntities(x => x.KeyValue_Id == primarykey).FirstOrDefault();
            if (KeyValue == null)
            {
                return HttpNotFound();
            }
            ViewBag.KeyValueName = Base_LocalService.GetWord("KeyValueName", CultureInfoName);
            return View(KeyValue);
        }

        [HttpPost]
        [AccountAuth(Roles = "Base_KeyValue_Edit")]
        public ActionResult Edit(Base_KeyValue KeyValue)
        {
            ModelMessage listMsg = new ModelMessage();
            if (ModelState.IsValid)
            {
                try
                {
                    Base_KeyValue bu = iBase_KeyValueService.LoadEntities(x => x.KeyValue_Id == KeyValue.KeyValue_Id).First();
                    bu.KeyValue_Name = KeyValue.KeyValue_Name;
                    bu.KeyValue_Sort = KeyValue.KeyValue_Sort;
                    bu.KeyValue_Remark = KeyValue.KeyValue_Remark;


                    bool result = iBase_KeyValueService.UpdateEntity(bu);

                    listMsg = new ModelMessage("ChangeResult", "m001", result ? "保存成功" : "保存失败");
                }
                catch (Exception e)
                {
                    listMsg = new ModelMessage("ChangeResult", "m002", "保存失败");
                }
            }
            return Json(listMsg);

        }

        [HttpPost]
        [AccountAuth(Roles = "Base_UserInfo_Edit")]
        public ActionResult ActivateSwich(string Ids, string activate = "N")
        {
            ModelMessage modelMessage = new ModelMessage();

            if (OperatorAvailable(Ids, activate))
            {
                modelMessage.Code = "m001";
                modelMessage.Message = "修改成功";
            }
            else
            {
                modelMessage.Code = "m002";
                modelMessage.Message = "修改失败";
            }
            return Json(modelMessage, JsonRequestBehavior.AllowGet);
        }

        private bool OperatorAvailable(string primarykeys, string available)
        {
            List<Guid> listBase_UserInfoGUID = primarykeys.Split(',').ToListGuid();
            List<Base_KeyValue> listBase_KeyValue = iBase_KeyValueService.LoadEntities(x => listBase_UserInfoGUID.Contains(x.KeyValue_Id)).ToList();
            foreach (var item in listBase_KeyValue)
            {
                item.KeyValue_Available = available;
            }
            int updaterow = iBase_KeyValueService.UpdateEntity();
            if (updaterow == 0)
            {
                return false;
            }
            return true;
        }



        [AccountAuth(Roles = "Base_KeyValue_FormelDUserlist")]
        public ActionResult FormelDUserlist()
        {
            ViewBag.SelectUser = Base_LocalService.GetWord("ProjectInfo_FormelDUser", CultureInfoName);
            ViewBag.KeyValue_UserNotNull = Base_LocalService.GetWord("KeyValue_UserNotNull", CultureInfoName);
            return View();
        }

        [AccountAuth(Roles = "Base_KeyValue_CustomerUserlist")]
        public ActionResult CustomerUserlist()
        {
            ViewBag.SelectUser = Base_LocalService.GetWord("ProjectInfo_CustomerUser", CultureInfoName);
            ViewBag.KeyValue_UserNotNull = Base_LocalService.GetWord("KeyValue_UserNotNull", CultureInfoName);
            return View();
        }


        [AccountAuth(Roles = "Base_KeyValue_Index")]
        public ActionResult SearchByCompany(string companyid)
        {
            List<Base_KeyValue> list = iBase_KeyValueService.LoadEntities(x => x.KeyValue_Available == "Y").OrderBy(x => x.KeyValue_Sort).ToList();

            Base_UserInfoService base_UserInfoService = new Base_UserInfoService();
            List<Base_UserInfo> listUser = base_UserInfoService.LoadEntities(x => x.User_Available == "Y").ToList();

            string keyword = GetRequestQueryString("keyword"); //"FormelD"

            List<Base_KeyValue> searchResult = null;

            if (string.IsNullOrEmpty(keyword))
            {
                searchResult = list;
            }
            else
            {

            }
            List<LayuiTree> listLayuitree = new List<LayuiTree>();
            foreach (var group in list.Where(x=>x.KeyValue_ParentId== new Guid("00000000-0000-0000-0000-000000000000") && x.KeyValue_CompanyCode== keyword))
            {
                LayuiTree layuitree = new LayuiTree() { id = group.KeyValue_Id.ToString(), title = group.KeyValue_Name };
                layuitree.children = new List<LayuiTree>();
                layuitree.spread = true;

                layuitree.attrName = "O";

                GetChildren(list, group.KeyValue_Id, layuitree, listUser);

                listLayuitree.Add(layuitree);
            }

            return Json(listLayuitree, JsonRequestBehavior.AllowGet);
        }

        private void GetChildren(List<Base_KeyValue> list, Guid parentguid, LayuiTree LayuiTree, List<Base_UserInfo> listuser)
        {

            var listchildren = list.Where(x => x.KeyValue_ParentId == parentguid).ToList();
            if (listchildren.Count > 0)
            {
                if (LayuiTree.children == null)
                {
                    LayuiTree.children = new List<LayuiTree>();
                }
                foreach (var group in listchildren)
                {
                    LayuiTree children = new LayuiTree() { id = group.KeyValue_Id.ToString(), title = group.KeyValue_Name };
                    children.attrName = "O";
                    children.icon = "fa-cogs";      
                   
                    //var listorgUser= listuser.Where(x => x.KeyValue_Id == group.KeyValue_Id).ToList();
                    //if (listorgUser.Count > 0)
                    //{
                    //    if (children.children == null)
                    //    {
                    //        children.children = new List<LayuiTree>();
                    //    }
                    //    foreach (var item in listorgUser)
                    //    {
                    //        LayuiTree usertree = new LayuiTree() { id = item.User_Id.ToString(), title = item.User_RealName };
                    //        usertree.attrName = "U";
                    //        //usertree.icon = "fa-user";

                    //        usertree.icon = "layui-icon layui-icon-friends";
                    //        usertree.leaf = "layui-icon-friends";

                    //        children.children.Add(usertree);
                    //    }
                    //}
                    GetChildren(list, group.KeyValue_Id, children, listuser);
                    LayuiTree.children.Add(children);

                }
            }

        }



        public ActionResult BindUserKeyValue() {
            ModelMessage listMsg = new ModelMessage();
           

            string CompanyType = GetRequestQueryString("CompanyType");
            string User_Id = GetRequestQueryString("User_Id");
            string ProjectId = GetRequestQueryString("ProjectId");


            //var result = new ProjectInfoService().UpdateProjectInfoUser(CompanyType, User_Id, ProjectId);
            //if (result)
            //{
            //    listMsg = new ModelMessage("ChangeResult", "m001", Base_LocalService.GetWord("SaveSucceed", CultureInfoName));
            //}
            //else {
            //    listMsg = new ModelMessage("ChangeResult", "m002", Base_LocalService.GetWord("SaveFailed", CultureInfoName));
            //}



            return Json(listMsg);

        }
    }
}
